// pages/dbdemo/dbdemo.js
Page({

  onLoad() {
    // 1. 获取数据库引用
    this.db = wx.cloud.database({
      env: "coursetest-4gdpfc295ac4eaea"
    })

    this.goodsCollection = this.db.collection('goods')
  },

  createGoods(e) {
    this.goodsCollection.add({
      // data 字段表示需新增的 JSON 数据
      data: {
        description: "learn cloud database",
        due: new Date("2018-09-01"),
        tags: [
          "cloud",
          "database"
        ],
        location: new this.db.Geo.Point(113, 23),
        done: false
      }
    })
      .then(res => {
        console.log("ok", res)
      })
      .catch(err => console.log("fail,err=", err))

  },

  retrieveOne(e) {
    this.goodsCollection.doc('0067b443625173220020b30e20cf8d6c').get({
      success: function (res) {
        // res.data 包含该记录的数据
        console.log(res.data)
      }
    })
  },

  async retrieveGoods(e) {
    try {
      const MAX_LIMIT = 20

      // 先取出集合记录总数
      const countResult = await this.goodsCollection.count()
      const total = countResult.total
      console.log("total", total);

      // 计算需分几次取
      const batchTimes = Math.ceil(total / MAX_LIMIT)//2
      const tasks = []

      for (let i = 0; i < batchTimes; i++) {
        const promise = this.goodsCollection.skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
        tasks.push(promise)
      }

      // 等待所有
      const result = (await Promise.all(tasks)).reduce((acc, cur) => {
        return {
          data: acc.data.concat(cur.data),
          errMsg: acc.errMsg,
        }
      })
      console.log("result=", result);
    } catch (err) {
      console.log("retrieveGoods:err=", err);
    }
  },

  updateGoods(e) {
    this.goodsCollection.doc('0067b443625173220020b32510876a5b').update({
      // data 传入需要局部更新的数据
      data: {
        // 表示将 done 字段置为 true
        t: "ta以一己之力掰弯了数百人"
      },
      success: function (res) {
        console.log("掰弯成功,res=",res)
      },
      fail(err){
        console.log("掰弯失败,err=",err);
      }
    })
  },

  deleteGoods(e) {
    this.goodsCollection.doc('d2fe6f2062517eac0604d5a403738df4').remove({
      success: function (res) {
        console.log("delete ok,res=", res)
      },
      fail(err) {
        console.log("delete fail,err=", err);
      }
    })
  },
})